
import $ from "jquery";
import "../../node_modules/signalr/jquery.signalR.min.js";

import { v4 } from 'uuid';
let serverInfo = {
    serverName: 'HaitianTPXStock-part-mian-computer172.18.47.100',
    serverID: '',
    listenArr: [],
};
var connection = $.hubConnection('http://172.18.59.193:9911/qdmes/');
var demoChatHubProxy = connection.createHubProxy('msghub');

//获取所有用户回调
demoChatHubProxy.on('getUsers', (message) => {
    let users = JSON.parse(message);
    let serverUser = users.find(item => item.Name === serverInfo.serverName);
    if (serverUser) {
        if (serverInfo.serverID != serverUser.ConnectionID) {
            serverInfo.serverID = serverUser.ConnectionID;
            // send('getAllListen', "");
        }
    }
    console.log(serverInfo);
});

connection.start().done(() => {
    // 连接成功后获取所有用户列表
    demoChatHubProxy.invoke('getName', "");

    console.log('已连接, connection ID=' + connection.id);
}).fail(() => {
    console.log('Could not connect');
});

async function start () {
    try {
        await connection.start();
        console.log("SignalR Connected.");
    } catch (err) {
        console.log(err);
        setTimeout(start, 10000);//错误重连
    }
}
//开始signalr连接
const connect = async () => {
    await start();
};
//调用服务端方法
async function send (methodName = 'sendMsg', param, isLight) {
    return new Promise(async (resolve, reject) => {
        try {
            if (methodName != 'getAllListen' && serverInfo.listenArr.length == 0) {
                await send('getAllListen', "");
            }
            let lightStr = [];
            for (let i = 0; i < param.length; i++) {
                let lightInfo = serverInfo.listenArr.find(item =>
                    item.IpAddress == param[i].IP
                    && item.Port == param[i].PORT
                );
                if (lightInfo) {
                    lightStr.push({
                        msgId: v4(),
                        Ip: param[i].IP,
                        Port: param[i].PORT,
                        interAddress: param[i].ADDRESS,
                        lightMode: param[i].MODE,
                        number: param[i].NUMBER,
                    });
                }
            }

            var msg = {
                Id: "",
                msgType: isLight ? "UpdateTagScreens" : "turnOffScreen",
                msgtxt: JSON.stringify(lightStr),
                Ip: "",
                port: ""
            };

            if (methodName == 'getAllListen') {
                msg.msgType = 'getAllListen';
                msg.msgtxt = '';
            }
            msg = JSON.stringify(msg);
            demoChatHubProxy.invoke('sendMsg', serverInfo.serverID, msg).done(result => {
                resolve(result);
            });
        }
        catch (err) {
            console.error(err);
        }

    });
}
// 服务器回调
demoChatHubProxy.on('addMessage', (message, connectionId) => {

    if (connectionId === serverInfo.serverID) {
        let msg = JSON.parse(message);
        // 通道回调
        if (msg.msgType === 'setAllListen') {
            let Listen = JSON.parse(msg.msgtxt);
            if (Listen.length != serverInfo.listenArr.length) {
                serverInfo.listenArr = Listen;
                console.log('Listen :>> ', Listen);
            }
        }
        // 亮灯回调
        else if (msg.msgType === 'hadTagScreens') {
            let resultArr = JSON.parse(msg.msgtxt);
            let failArr = resultArr.filter(el => !el.resultStr.includes('成功'));
            if (resultArr.length != 0 && failArr.length == 0) {
                console.log('亮灯成功');
            } else {
                console.log('亮灯失败');
            }
        }
        // 拍灯回调
        else if (msg.msgType == "onPush_TAL600_Process" || msg.msgType == "onPush_Process") {
            let light = JSON.parse(msg.msgtxt);
            console.log('light :>> ', light);
        }
        return;
    }
    console.log('connectionId :>> ', connectionId);
});

//断开连接
const disconnect = async () => {
    await connection.stop();
};

export {
    serverInfo,
    connection,
    connect,
    send,
    disconnect,
};